package com.ahua.mallchat.common.exception;

import com.ahua.mallchat.common.domain.enums.system.CommonErrorEnum;
import com.ahua.mallchat.common.domain.vo.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(","));

        return ApiResult.fail(CommonErrorEnum.PARAM_VALID.getErrorCode(), errorMsg.substring(0, errorMsg.length() - 1));
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = BusinessException.class)
    public ApiResult businessException(BusinessException e) {
        log.info("business exception! The reason is:{}", e.getMessage());
        return ApiResult.fail(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 兜底的异常（最大的异常类）
     */
    @ExceptionHandler(value = Throwable.class)
    public ApiResult throwable(Throwable e) {
        log.error("System exception! The reason is:{}", e);
        return ApiResult.fail(CommonErrorEnum.SYSTEM_ERROR);
    }
}
